package com.driving.single.common.redis.service.impl;

import com.driving.single.common.redis.service.CommonRedisSendSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class CommonRedisSendSmsServiceImpl implements CommonRedisSendSmsService {
    @Value("${redis_key_sms_register}")
    private String redis_key_sms_register;  // 用户注册SMS验证码KEY
    @Value("${redis_key_sms_register_expire_minute}")
    private Integer redis_key_sms_register_expire_minute;   // 用户注册SMS验证码过期时间(单位：分)
    @Value("${redis_key_sms_login}")
    private String redis_key_sms_login;  // 用户登录SMS验证码KEY
    @Value("${redis_key_sms_login_expire_minute}")
    private Integer redis_key_sms_login_expire_minute;   // 用户登录SMS验证码过期时间(单位：分)

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 向 Redis 中存入 用户注册验证码
     * @param phoneNumbers 用户手机号
     * @param code         注册验证码
     */
    @Override
    public Integer insertRegisterCodeToRedis(String phoneNumbers, String code) {
        String key = this.redis_key_sms_register + ":" + phoneNumbers;
        this.redisTemplate.opsForValue().set(key, code, this.redis_key_sms_register_expire_minute, TimeUnit.MINUTES);
        return 200;
    }

    /**
     * 获取用户注册验证码
     * @param phoneNumbers 用户手机号
     * @return code,注册验证码
     */
    @Override
    public String selectRegisterCodeFromRedis(String phoneNumbers) {
        String key = this.redis_key_sms_register + ":" + phoneNumbers;
        return (String) this.redisTemplate.opsForValue().get(key);
    }

    /**
     * 向 Redis 中存入 用户登录验证码
     * @param phoneNumbers 用户手机号
     * @param code         登录验证码
     */
    @Override
    public Integer insertLoginCodeToRedis(String phoneNumbers, String code) {
        String key = this.redis_key_sms_login + ":" + phoneNumbers;
        this.redisTemplate.opsForValue().set(key, code, this.redis_key_sms_login_expire_minute, TimeUnit.MINUTES);
        return 200;
    }

    /**
     * 获取用户登录验证码
     * @param phoneNumbers 用户手机号
     * @return code,注册验证码
     */
    @Override
    public String selectLoginCodeFromRedis(String phoneNumbers) {
        String key = this.redis_key_sms_login + ":" + phoneNumbers;
        return (String) this.redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除Redis登录验证码缓存
     * @param phoneNumbers 用户手机号
     */
    @Override
    public Boolean deleteLoginCodeFromRedis(String phoneNumbers) {
        String key = this.redis_key_sms_login + ":" + phoneNumbers;
        return this.redisTemplate.delete(key);
    }
}
